<template>
  <div>
    <div v-if="currentValue && currentValue.attachmentId" style="margin-bottom: 10px;">
      <ul>
        <li>
          <div>
            <a target="_blank" :href="currentValue.url">{{ currentValue.friendlyFileName }}</a>
            <i class="i-remove el-icon-circle-close" title="移除" @click="deleteItem(currentValue)"></i>
          </div>
        </li>
      </ul>
    </div>
    <file-dialog ref="fileDialog" file-type="file" :allowed-extension="allowedExtension" :file-max-size="10" @save="getSelectedItem"></file-dialog>
    <el-button @click="open()">选择文件</el-button>
  </div>
</template>

<script>
import FileDialog from "@/components/ApeSelectors/file-dialog";

export default {
  name: "ApeFileSingleSelector",
  components: {
    FileDialog
  },
  props: {
    allowedExtension: {
      type: Array,
      default: () => {
        return [];
      }
    },
    attachmentId: {
      type: Number,
      default: 0
    },
    value: {
      type: Object,
      default: () => {
        return undefined;
      }
    }
  },
  data() {
    return {
      currentValue: this.value
    };
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  methods: {
    updateValue(newValue) {
      this.$emit("input", newValue);
      this.$emit("select");
    },
    // 从已选图片列表中删除某张图片
    deleteItem(item) {
      this.currentValue = undefined;
      this.updateValue(this.currentValue);
    },
    // 打开选择图片和上传图片的Dialog
    open() {
      this.$refs["fileDialog"].open();
    },
    getSelectedItem(selectedItem) {
      const item = selectedItem;
      item.display_order = 0;
      this.currentValue = item;
      this.updateValue(this.currentValue);
    }
  }
};
</script>
<style lang="scss">
</style>
